import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, UserPageQuery, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import * as api from './api';
import { auth } from "/@/utils/authFunction";
import { ElMessage } from 'element-plus';
import { h } from 'vue';

export default function ({ crudExpose }: { crudExpose: CrudExpose }): CreateCrudOptionsRet {
    const pageRequest = async (query: any) => {
        return await api.GetList(query);
    };
    const editRequest = async ({ form, row }: EditReq) => {
        if (row.id) {
            form.id = row.id;
        }
        console.log('编辑表单数据:', form);
        return await api.UpdateObj(form);
    };
    const delRequest = async ({ row }: DelReq) => {
        return await api.DelObj(row.id);
    };
    const addRequest = async ({ form }: AddReq) => {
        form.status = 1;
        return await api.AddObj(form);
    };

    const exportRequest = async (query: UserPageQuery) => {
        return await api.exportData(query)
    };

    return {
        crudOptions: {
            request: {
                pageRequest,
                addRequest,
                editRequest,
                delRequest,
            },
            actionbar: {
                buttons: {
                    export: {
                        show: auth('MaintenanceRecord:Export'),
                        text: "导出",
                        title: "导出",
                        click() {
                            return exportRequest(crudExpose.getSearchFormData())
                        }
                    },
                    add: {
                        show: auth('MaintenanceRecord:Create'),
                    },
                }
            },
            rowHandle: {
                fixed: 'right',
                width: 200,
                buttons: {
                    view: {
                        type: 'text',
                        order: 1,
                        show: auth('MaintenanceRecord:Retrieve')
                    },
                    edit: {
                        type: 'text',
                        order: 2,
                        show: auth('MaintenanceRecord:Update')
                    },
                    copy: {
                        type: 'text',
                        order: 3,
                        show: auth('MaintenanceRecord:Copy')
                    },
                    remove: {
                        type: 'text',
                        order: 4,
                        show: auth('MaintenanceRecord:Delete')
                    },
                },
            },
            form: {
                beforeSubmit({ form }) {
                    if (!form.completion_date) {
                        ElMessage.error('完成时间必填');
                        return false;
                    }
                    if (new Date(form.completion_date) > new Date()) {
                        ElMessage.error('完成时间不能晚于当前时间');
                        return false;
                    }
                    return true;
                }
            },
            columns: {
                device: {
                    title: '设备',
                    type: 'dict-select',
                    search: { show: true },
                    dict: dict({
                        url: '/api/device/',
                        value: 'id',
                        label: 'name',
                        async onReady({ dict }) {
                            await dict.loadDict();
                        }
                    }),
                    form: {
                        rules: [{ required: true, message: '设备必选' }],
                        component: {
                            placeholder: '请选择设备',
                            filterable: true,
                            clearable: true,
                        }
                    },
                    column: {
                        minWidth: 120,
                        showOverflowTooltip: true
                    }
                },
                maintenance_type: {
                    title: '维护类型',
                    type: 'dict-select',
                    search: { show: true },
                    dict: dict({
                        data: [
                            { value: 1, label: '定期保养' },
                            { value: 2, label: '故障维修' },
                            { value: 3, label: '设备升级' }
                        ]
                    }),
                    form: {
                        rules: [{ required: true, message: '维护类型必选' }],
                        component: {
                            placeholder: '请选择维护类型'
                        }
                    },
                    column: {
                        width: 100,
                        sortable: 'custom',
                        align: 'center',
                        formatter: ({ row }: { row: any }) => {
                            const statusMap: Record<number, { text: string; type: string }> = {
                                1: { text: '定期保养', type: 'success' },
                                    2: { text: '故障维修', type: 'danger' },
                                    3: { text: '设备升级', type: 'primary' }
                            };
                            const status = statusMap[row.maintenance_type] || { text: row.maintenance_type, type: 'info' };
                            return <el-tag size="small" type={status.type}>{status.text}</el-tag>;
                        }
                    },
                },
                status: {
                    title: '状态',
                    type: 'dict-select',
                    search: { show: true },
                    dict: dict({
                        data: [
                            { value: 1, label: '待审批' },
                            { value: 2, label: '已审批' },
                            { value: 3, label: '进行中' },
                            { value: 4, label: '已完成' }
                        ]
                    }),
                    form: {
                        value: 1,
                        rules: [{ required: true, message: '状态必选' }]
                    },
                    column: {
                        width: 100,
                        sortable: 'custom',
                        align: 'center',
                        formatter: ({ row }: { row: any }) => {
                            const statusMap: Record<number, { text: string; type: string }> = {
                                1: { text: '待审批', type: 'warning' },
                                2: { text: '已审批', type: 'success' },
                                3: { text: '进行中', type: 'primary' },
                                4: { text: '已完成', type: 'info' }
                            };
                            const status = statusMap[row.status] || { text: row.status, type: 'info' };
                            return <el-tag size="small" type={status.type}>{status.text}</el-tag>;
                        }
                    },
                    addForm: {
                        component: {
                            placeholder: '请选择状态',
                            disabled: true // 添加模式下禁用
                        },
                        helper: { render: () => h('div', { style: { color: '#909399' } }, '新建记录状态默认为"待审批"，无法更改') }
                    },
                    editForm: {
                        component: {
                            placeholder: '请选择状态',
                            disabled: false // 编辑模式下启用
                        }
                    }
                },
                description: {
                    title: '维护内容',
                    type: 'textarea',
                    search: { show: false },
                    form: {
                        rules: [{ required: true, message: '维护内容必填' }],
                        component: {
                            placeholder: '请输入维护内容',
                            showWordLimit: true,
                            maxlength: 500,
                            rows: 4
                        }
                    },
                    column: {
                        minWidth: 200,
                        showOverflowTooltip: true
                    }
                },
                completion_date: {
                    title: '完成时间',
                    type: 'date',
                    search: { show: true },
                    form: {
                        rules: [{ required: true, message: '完成时间必填' }],
                        component: {
                            format: "YYYY-MM-DD",
                            valueFormat: "YYYY-MM-DD",
                            placeholder: '请选择完成时间'
                        }
                    },
                    column: {
                        align: "center",
                        width: 120,
                        component: { name: "fs-date-format", format: "YYYY-MM-DD" }
                    }
                },
            },
        },
    };
} 